package com.yizisu.basemvvm.widget

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.yizisu.basemvvm.mvvm.MvvmPopupWindow
import com.yizisu.basemvvm.mvvm.mvvm_helper.BaseMvvmInterface
import com.yizisu.basemvvm.utils.permission.PermissionUtil

/**
 * 若红楼梦空，亦初心不变
 * 作者：thinker
 * 包名：com.yizisu.basemvvm.widget
 * 时间：2019/5/30 16:44
 * 描述：子类实现的popupWindow
 * 描述：直接new出来的请操作MvvmPopupWindow
 */
abstract class BasePopupWindow(ctx: Context) : MvvmPopupWindow(ctx), BaseMvvmInterface {
    final override fun getPermission(permission: MutableList<String>, needPermissionCall: (Boolean) -> Unit) {
        PermissionUtil.request(permission) {
            needPermissionCall.invoke(it.isEmpty())
        }
    }

    override fun getClickView(): List<View?>? = null

    override fun initViewModel() {
    }

    override fun initUi(savedInstanceState: Bundle?) {
    }

    override fun initData() {
    }

    override fun onSingleClick(view: View) {
    }

    init {
        contentView = onCreateView(LayoutInflater.from(context))
        onViewCreated()
    }

    /**
     * 创建view
     */
    private fun onCreateView(inflater: LayoutInflater): View {
        return when (val contentView = getLayoutResOrView(inflater)) {
            is Int -> {
                inflater.inflate(contentView, null, false)
            }
            is View -> {
                contentView
            }
            else -> {
                throw IllegalArgumentException("getLayoutResOrView() only return view/LayoutRes")
            }
        }
    }

    /**
     * 模仿onCreate调用方法
     */
    private fun onViewCreated() {
        initViewModel()
        initUi(null)
        getClickView()?.forEach {
            it?.setOnClickListener(this)
        }
        initData()
    }
}